<template>
  <div class="intelligent-command-container">
    <!-- 头部控制栏 -->
    <div class="control-header">
      <div class="header-left">
        <el-icon class="control-icon"><ChatDotRound /></el-icon>
        <span class="control-title">智能指令</span>
      </div>
      
      <div class="header-controls">

        <button class="control-btn" @click="clearChat">
          <el-icon><Delete /></el-icon>
        </button>
      </div>
    </div>
    
    <!-- 聊天对话区域 -->
    <div class="chat-section">
      <div class="chat-messages" ref="chatMessages">
        <div 
          v-for="message in chatHistory" 
          :key="message.id"
          class="chat-message"
          :class="message.type"
        >
          <div class="message-bubble" :class="message.type">
            <div class="message-content">{{ message.content }}</div>
            <div v-if="message.image" class="message-image">
              <img :src="message.image" alt="任务结果" />
            </div>
          </div>
          <div class="message-time">{{ message.time }}</div>
        </div>
        
        <!-- 任务完成分隔符 -->
        <div v-if="showTaskComplete" class="task-complete">
          <span>任务已完成 - {{ completionTime }}</span>
        </div>
      </div>
      
      <!-- 快捷指令 -->
      <div class="quick-commands">
        <button 
          v-for="cmd in quickCommands" 
          :key="cmd.id"
          class="quick-cmd-btn"
          @click="sendQuickCommand(cmd)"
        >
          {{ cmd.text }}
        </button>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input-area">
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            placeholder="输入指令或语音控制..."
            @keyup.enter="sendMessage"
            class="message-input"
          />
          <button 
            class="voice-btn" 
            :class="{ active: isListening }"
            @click="toggleVoiceInput"
          >
            <el-icon><Microphone /></el-icon>
          </button>
          <button class="send-btn" @click="sendMessage">
            <el-icon><Promotion /></el-icon>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { 
  ChatDotRound, Microphone, Delete, Promotion 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 定义 emits
const emit = defineEmits(['command-sent', 'voice-toggle', 'chat-cleared'])

const chatMessages = ref(null)
const inputMessage = ref('')
const isListening = ref(false)
const showTaskComplete = ref(false)
const completionTime = ref('')

const chatHistory = ref([
  {
    id: 1,
    type: 'user',
    content: '前往会议室A并拍照',
    time: '10:30:45 • 已执行'
  },
  {
    id: 2,
    type: 'system',
    content: '会议室A图像采集完成',
    time: '10:35:12',
    image: 'https://miaoduo.fbcontent.cn/private/resource/image/199280a6a6394b8-01065932-7095-4b05-b496-25289fa52e4f.jpeg'
  }
])

const quickCommands = ref([
  { id: 1, text: '移动指令', command: 'move' },
  { id: 2, text: '拍照指令', command: 'photo' },
  { id: 3, text: '环境感知', command: 'sense' },
  { id: 4, text: '返回充电', command: 'charge' },
  { id: 5, text: '巡逻模式', command: 'patrol' },
  { id: 6, text: '跟随模式', command: 'follow' }
])

// 聊天功能
const sendMessage = () => {
  if (!inputMessage.value.trim()) return
  
  const message = {
    id: Date.now(),
    type: 'user',
    content: inputMessage.value,
    time: new Date().toLocaleTimeString()
  }
  
  chatHistory.value.push(message)
  
  // 发送指令到父组件
  emit('command-sent', {
    type: 'text',
    content: inputMessage.value,
    timestamp: new Date().toISOString()
  })
  
  inputMessage.value = ''
  
  // 模拟系统回复
  setTimeout(() => {
    const reply = {
      id: Date.now() + 1,
      type: 'system',
      content: '指令已接收，正在执行...',
      time: new Date().toLocaleTimeString()
    }
    chatHistory.value.push(reply)
    scrollToBottom()
  }, 1000)
  
  scrollToBottom()
}

const sendQuickCommand = (command) => {
  const message = {
    id: Date.now(),
    type: 'user',
    content: command.text,
    time: new Date().toLocaleTimeString()
  }
  
  chatHistory.value.push(message)
  
  // 发送快捷指令到父组件
  emit('command-sent', {
    type: 'quick',
    command: command.command,
    content: command.text,
    timestamp: new Date().toISOString()
  })
  
  // 模拟系统回复
  setTimeout(() => {
    let replyContent = ''
    switch (command.command) {
      case 'move':
        replyContent = '移动控制已激活，请使用手动控制面板'
        break
      case 'photo':
        replyContent = '拍照功能已启动，正在采集图像...'
        break
      case 'sense':
        replyContent = '环境感知系统已启动，正在分析周围环境...'
        break
      case 'charge':
        replyContent = '正在规划返回充电站路径...'
        break
      case 'patrol':
        replyContent = '巡逻模式已启动，开始自动巡逻...'
        break
      case 'follow':
        replyContent = '跟随模式已启动，请保持在视野范围内...'
        break
      default:
        replyContent = '指令已接收，正在执行...'
    }
    
    const reply = {
      id: Date.now() + 1,
      type: 'system',
      content: replyContent,
      time: new Date().toLocaleTimeString()
    }
    chatHistory.value.push(reply)
    scrollToBottom()
  }, 800)
  
  scrollToBottom()
}

const toggleVoiceInput = () => {
  isListening.value = !isListening.value
  
  emit('voice-toggle', isListening.value)
  
  if (isListening.value) {
    ElMessage.info('语音识别已启动')
    console.log('开始语音识别')
  } else {
    ElMessage.info('语音识别已停止')
    console.log('停止语音识别')
  }
}



const clearChat = () => {
  chatHistory.value = []
  showTaskComplete.value = false
  emit('chat-cleared')
  ElMessage.success('聊天记录已清空')
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessages.value) {
      chatMessages.value.scrollTop = chatMessages.value.scrollHeight
    }
  })
}

// 添加新消息的方法（供父组件调用）
const addMessage = (message) => {
  chatHistory.value.push({
    id: Date.now(),
    type: message.type || 'system',
    content: message.content,
    time: message.time || new Date().toLocaleTimeString(),
    image: message.image
  })
  scrollToBottom()
}

// 设置任务完成状态
const setTaskComplete = (completed = true) => {
  showTaskComplete.value = completed
  if (completed) {
    completionTime.value = new Date().toLocaleTimeString()
  }
}

// 暴露方法供父组件调用
defineExpose({
  addMessage,
  setTaskComplete,
  clearChat,
  chatHistory
})

onMounted(() => {
  scrollToBottom()
  
  // 模拟任务完成
  setTimeout(() => {
    setTaskComplete(true)
  }, 3000)
})
</script>

<style scoped>
.intelligent-command-container {
  background: rgba(10, 25, 47, 0.9);
  backdrop-filter: blur(8px);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.control-header {
  background: var(--secondary-bg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  height: 28px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 4px;
}

.control-icon {
  color: var(--primary-blue);
  font-size: 14px;
}

.control-title {
  color: var(--text-primary);
  font-size: 13px;
  font-weight: 500;
  line-height: 1;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 4px;
}

.control-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  transition: color 0.3s ease;
  font-size: 12px;
}

.control-btn:hover {
  color: var(--primary-blue);
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--primary-bg);
  min-height: 0;
}

.chat-messages {
  flex: 1;
  padding: 8px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-height: 0;
}

.chat-message {
  display: flex;
  flex-direction: column;
}

.chat-message.user {
  align-items: flex-end;
}

.chat-message.system {
  align-items: flex-start;
}

.message-bubble {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-bubble.user {
  background: var(--secondary-blue);
  color: var(--text-primary);
  border-radius: 8px 0px 8px 8px;
}

.message-bubble.system {
  background: var(--secondary-bg);
  color: var(--text-secondary);
  border-radius: 0px 8px 8px 8px;
}

.message-content {
  font-size: 13px;
  line-height: 1.4;
}

.message-image {
  margin-top: 8px;
  border-radius: 6px;
  overflow: hidden;
}

.message-image img {
  width: 100%;
  height: auto;
  display: block;
}

.message-time {
  font-size: 11px;
  color: var(--text-secondary);
  margin-top: 4px;
  opacity: 0.8;
}

.task-complete {
  background: var(--secondary-bg);
  border-radius: 9999px;
  padding: 4px 12px;
  text-align: center;
  margin: 8px auto;
  font-size: 12px;
  color: var(--text-secondary);
}

.quick-commands {
  padding: 6px 8px;
  border-top: 1px solid var(--border-color);
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  flex-shrink: 0;
}

.quick-cmd-btn {
  background: var(--secondary-bg);
  border: none;
  border-radius: 9999px;
  padding: 4px 10px;
  font-size: 12px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.3s ease;
}

.quick-cmd-btn:hover {
  background: var(--primary-blue);
  color: var(--text-primary);
}

.chat-input-area {
  padding: 8px;
  border-top: 1px solid var(--border-color);
  background: var(--accent-bg);
  flex-shrink: 0;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.input-container {
  display: flex;
  gap: 4px;
  align-items: center;
}

.message-input {
  flex: 1;
}

.voice-btn, .send-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: var(--secondary-bg);
  color: var(--text-secondary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.voice-btn:hover, .send-btn:hover {
  background: var(--primary-blue);
  color: var(--text-primary);
}

.voice-btn.active {
  background: #EF4444;
  color: white;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}
</style>